/**
 * Copyright 2019-2022 Huawei Technologies Co., Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "framework/graph/core/optimize/schedule/node_pass_list.h"

#include <map>
#include <vector>

#include "infra/base/securestl.h"

#include "framework/graph/core/node/node.h"
#include "framework/graph/core/node/node_fwd.h"
#include "framework/graph/core/node/node_spec.h"
#include "framework/graph/core/node/node_visitor.h"

#include "framework/graph/core/optimize/schedule/node_pass.h"

namespace hiai {
class NodePassListImpl : public NodePassList {
private:
    void Add(std::unique_ptr<INodePass> pass) override;
    OptimizeStatus Optimize(ge::Node& node, ge::ComputeGraph& graph, NodeValidater validater) override;
    bool Attention(const std::string& type) const override;

private:
    std::vector<std::unique_ptr<INodePass>> passes_;
    std::map<std::string, std::vector<INodePass*>> passesMap_;
};

void NodePassListImpl::Add(std::unique_ptr<INodePass> pass)
{
    for (const auto& type : pass->AttentionNodeTypes()) {
        passesMap_[type].emplace_back(pass.get());
    }
    passes_.emplace_back(std::move(pass));
}

OptimizeStatus NodePassListImpl::Optimize(ge::Node& node, ge::ComputeGraph& graph, NodeValidater validater)
{
    OptimizeStatus passStatus = OptimizeStatus::OPTIMIZE_NOT_CHANGED;
    if (!validater(node)) {
        return passStatus;
    }
    
    const std::string& type = node.ROLE(NodeSpec).Type();
    for (const auto& pass : passesMap_[type]) {
        if (validater(node)) {
            OptimizeStatus ret = pass->Run(node, graph);
            if (ret == OptimizeStatus::OPTIMIZE_FAILED) {
                return OptimizeStatus::OPTIMIZE_FAILED;
            } else if (ret == OptimizeStatus::OPTIMIZE_CHANGED) {
                passStatus = OptimizeStatus::OPTIMIZE_CHANGED;
            }
        }
    }

    return passStatus;
}

bool NodePassListImpl::Attention(const std::string& type) const
{
    return passesMap_.count(type);
}

std::unique_ptr<NodePassList> NodePassList::Make()
{
    return make_unique_nothrow<NodePassListImpl>();
}
} // namespace hiai